package com.hmall.gateway.filter;


import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component           // 类名后缀GatewayFilterFactory
public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<PrintAnyGatewayFilterFactory.Config> { // 不加参泛型是Object

    @Override
    public GatewayFilter apply(Config config) {
        return new OrderedGatewayFilter(new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String a = config.getA();
                System.out.println("a = " + a);
                String b = config.getB();
                System.out.println("b = " + b);
                String c = config.getC();
                System.out.println("c = " + c);

                //编写过滤器逻辑
                System.out.println("PrintAny filter执行了");
                // 放行
                return chain.filter(exchange);
            }
        },1);
    }

// 有参
    //自定义配置属性，成员变量名称很重要，下面会用到
    @Data
    public static class Config{
        private String a;
        private String b;
        private String c;
    }
    //将变量名称依次返回，顺序很重要，将来读取参数时需要按顺序获取
    @Override
    public List<String> shortcutFieldOrder(){
        return List.of("a","b","c");
    }

    // 将Config字节码传递给父类，父类负责帮我们读现yaml配置
    public PrintAnyGatewayFilterFactory() {
        super(Config.class);
    }
}
